package cn.edu.scnu.semart.goods.service.Impl;

import cn.edu.scnu.semart.model.goods.Category;
import cn.edu.scnu.semart.goods.mapper.CategoryMapper;
import cn.edu.scnu.semart.goods.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品分类Service实现类
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getAllCategories() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1).orderByAsc("sort_order");
        return list(queryWrapper);
    }

    @Override
    public List<Category> getCategoriesByParentId(Integer parentId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId)
                   .eq("status", 1)
                   .orderByAsc("sort_order");
        return list(queryWrapper);
    }

    @Override
    public List<Category> getCategoryTree() {
        List<Category> allCategories = getAllCategories();
        
        // 构建分类树
        Map<Integer, List<Category>> parentMap = allCategories.stream()
                .collect(Collectors.groupingBy(Category::getParentId));
        
        return buildCategoryTree(parentMap, 0);
    }

    private List<Category> buildCategoryTree(Map<Integer, List<Category>> parentMap, Integer parentId) {
        List<Category> children = parentMap.get(parentId);
        if (children == null) {
            return new ArrayList<>();
        }
        
        for (Category category : children) {
            List<Category> childList = buildCategoryTree(parentMap, category.getId());
            // 这里可以设置子分类，如果需要的话
        }
        
        return children;
    }

    @Override
    public boolean addCategory(Category category) {
        // 设置默认值
        if (category.getStatus() == null) {
            category.setStatus(1);
        }
        if (category.getSortOrder() == null) {
            category.setSortOrder(0);
        }
        if (category.getLevel() == null) {
            category.setLevel(1);
        }
        
        return save(category);
    }

    @Override
    public boolean updateCategory(Category category) {
        return updateById(category);
    }

    @Override
    public boolean deleteCategory(Integer id) {
        // 检查是否有子分类
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = Math.toIntExact(count(queryWrapper));
        if (count > 0) {
            throw new RuntimeException("该分类下有子分类，无法删除");
        }
        
        return removeById(id);
    }
} 